<?php

namespace app\common\model;

use app\common\model\TimeModel;
use think\Exception;

class TaskUser extends TimeModel
{

    protected $name = "task_user";

    protected $deleteTime = false;

    const TABLE_NAME = 'task_user';

    const STATUS_DOING = 0;
    const STATUS_FINISH = 1;
    const STATUS_EVALUATE = 2;
    public static $statusMap = array(
        self::STATUS_DOING => '进行中',
        self::STATUS_FINISH => '已完成',
        self::STATUS_EVALUATE => '已评价'
    );

    /**
     * 状态流
     *
     * @var array
     */
    public static $statusFlow = array(
        self::STATUS_DOING => array(
            self::STATUS_FINISH,
        ),
        self::STATUS_FINISH => array(
            self::STATUS_EVALUATE
        )
    );

    // 删除状态
    const DELETE_NO = 0;
    const DELETE_YES = 1;


    /**
     * 获取 列表信息
     *
     * @param array $conditions
     * @param int $page
     * @param int $page_size
     * @param string $order
     * @return mixed
     * @throws Exception
     */
    public function getListInfo($conditions=[], $page=1, $page_size=10, $order='a.id desc')
    {

        $new_conditions = $conditions;
        $new_conditions[] = array('a.is_del', '=', self::DELETE_NO);
        try {
            $join = [
                ['ea_system_user user', 'a.claim_uid=user.id', 'left'],
                ['ea_task_release task', 'a.task_id=task.id', 'left']
            ];
            $field = 'a.*, user.user_name as claim_user_name, task.title as task_title';
            $result = model(self::TABLE_NAME)->pageList($new_conditions, $field, $order, $page, $page_size, 'a', $join);
            foreach($result['list'] as $key => $info){
                $result['list'][$key]['status_cn'] = self::getStatusCn($info['status']);
            }
            return $result;
        }catch (\Exception $e){
            self::writeLog([
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('查询失败');
        }
    }

    /**
     * 获取 任务详情
     *
     * @param $conditions
     * @return mixed
     * @throws Exception
     */
    public function getDetail($conditions)
    {

        $new_conditions = $conditions;
        $new_conditions[] = array('a.is_del', '=', self::DELETE_NO);
        try {
            $join = [
                ['ea_system_user user', 'a.claim_uid=user.id', 'left'],
                ['ea_task_release task', 'a.task_id=task.id', 'left']
            ];
            $field = 'a.*, user.user_name as claim_user_name, task.title as task_title';
            $result = model(self::TABLE_NAME)->getInfo($new_conditions, $field, 'a', $join);
            if(empty($result)){ throw new Exception('任务不存在'); }
            $result['status_cn'] = self::getStatusCn($result['status']);
            return $result;
        }catch (\Exception $e){
            self::writeLog([
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('查询失败');
        }
    }

    /**
     * 任务完成
     *
     * @param $conditions
     * @param $data
     * @return int
     * @throws Exception
     */
    public function updateInfo($conditions, $data)
    {

        $new_data = $new_conditions = array();
        !isset($data['task_id']) ?: $new_data['task_id'] = $data['task_id'];
        !isset($data['img']) ?: $new_data['finish_img'] = $data['img'];
        !isset($data['status']) ?: $new_data['status'] = $data['status'];
        !isset($data['deal_uid']) ?: $new_data['deal_uid'] = $data['deal_uid'];
        !isset($data['evaluate_desc']) ?: $new_data['evaluate_desc'] = $data['evaluate_desc'];
        !isset($data['score']) ?: $new_data['score'] = $data['score'];
        !isset($data['evaluate_time']) ?: $new_data['evaluate_time'] = $data['evaluate_time'];
        !isset($data['finish_time']) ?: $new_data['finish_time'] = $data['finish_time'];

        // 任务有效性 校验
        $new_conditions = $conditions;
        $task_user_info = model(self::TABLE_NAME)->getInfo($new_conditions);
        if(empty($task_user_info)){ throw new Exception('任务不存在'); }

        // 状态流转 校验
        if(isset($new_data['status'])){
            try{
                self::checkStatusFlow($task_user_info['status'], $new_data['status']);
            }catch (\Exception $e){
                throw new Exception($e->getMessage());
            }
        }

        // 更新
        try{
            return model(self::TABLE_NAME)->updateInfo($new_data, $new_conditions);
        }catch (\Exception $e){
            self::writeLog([
                'data' => $new_data,
                'conditions' => $new_conditions,
                'msg' => $e->getMessage(),
                'sql' => lastSql()
            ]);
            throw new Exception('操作失败');
        }
    }

    /**
     * 任务完成
     *
     * @param $data
     * @param $user_id
     * @return int
     * @throws Exception
     */
    public function completed($data, $user_id)
    {

        $new_data = $task_user_conditions = array();
        $new_data['task_id'] = isset($data['task_id']) ? $data['task_id'] : '';
        $new_data['finish_img'] = isset($data['img']) ? $data['img'] : '';
        if(empty($new_data['task_id']) || empty($new_data['finish_img'])){
            throw new Exception('参数有误');
        }

        // 任务有效性 校验
        $task_user_conditions[] = ['task_id', '=', $new_data['task_id']];
        $task_user_conditions[] = ['claim_uid', '=', $user_id];
        $task_user_info = model(self::TABLE_NAME)->getInfo($task_user_conditions);
        if(empty($task_user_info)){ throw new Exception('任务不存在'); }

        // 状态流转 校验
        $next_status = self::STATUS_FINISH;
        try{
            self::checkStatusFlow($task_user_info['status'], $next_status);
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }

        // 更新
        $new_data['status'] = $next_status;
        $new_data['finish_time'] = date('Y-m-d H:i:s');
        try{
            return model(self::TABLE_NAME)->updateInfo($new_data, $task_user_conditions);
        }catch (\Exception $e){
            throw new Exception('操作失败');
        }
    }

    /**
     * 状态流转 校验
     *
     * @param $cur_status
     * @param $next_status
     * @return bool
     * @throws Exception
     */
    public static function checkStatusFlow($cur_status, $next_status)
    {

        if(!isset(self::$statusFlow[$cur_status])){ throw new Exception('当前状态有误'); }
        elseif(in_array($next_status, self::$statusFlow[$cur_status]) === false){
            throw new Exception('状态流转有误');
        }

        return true;
    }

    /**
     * 状态描述
     *
     * @param $status
     * @return mixed|string
     */
    public static function getStatusCn($status)
    {

        return isset(self::$statusMap[$status]) ? self::$statusMap[$status] : '';
    }
}